<template>
  <!-- 地图 -->
  <div class="mapContent">
    <div class="cardTitle">
      充电站点分布地图
      <a-icon type="link" class="linkIcon" />
    </div>
    <div class="mapChart" ref="map">
      <!-- 添加图例 -->
    </div>
    <div class="mapLegend">
      <div class="legendItem">
        <span class="legendDot blue"></span>
        <span class="legendText">1-10台</span>
      </div>
      <div class="legendItem">
        <span class="legendDot green"></span>
        <span class="legendText">10-50台</span>
      </div>
      <div class="legendItem">
        <span class="legendDot yellow"></span>
        <span class="legendText">50-100台</span>
      </div>
    </div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import china from "../../json/china.json";
import gd from "../../json/gdAll.json";


const props = defineProps({
  provinceId: {
    type: Number,
    default: "广东省", // 默认为广东省
  },
  mapsData: {
    type: Array,
    default: () => [],
  },
  provinceData: {
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(["provinceClick", "backToNation"]);
const map = ref(null);
const mapInstance = ref(null);
const currentMapLevel = ref("province");
const currentProvince = ref("广东省"); // 默认为广东省
const handleResize = () => {
  if (mapInstance.value) {
    mapInstance.value.resize();
  }
};
// 省份坐标数据
const provinceCoordMap = {
  广东省: [113.280637, 23.125178],
};

// 初始化地图
const initMap = () => {
  if (mapInstance.value) {
    mapInstance.value.off("click");
    mapInstance.value.dispose();
  }

  // 注册地图
  echarts.registerMap("china", china);

  // 初始化地图实例
  mapInstance.value = echarts.init(map.value);

  // 根据当前级别显示不同地图
  if (currentMapLevel.value === "nation") {
    showNationMap();
  } else {
    showProvinceMap(currentProvince.value);
  }
  window.addEventListener("resize", handleResize);
};

// tooltip 配置
const getTooltipConfig = () => {
  return {
    trigger: "item",
    formatter: function (params) {
      if (params.data) {
        const cityName = params.name;
        let displayCount = 0;
        let displayText = "个电站";

        // 根据当前地图级别显示不同的数据
        if (currentMapLevel.value === "nation") {
          // 全国维度省份下的电站总数
          displayCount =
            params.data.stationCount || params.data.provinceNum || 1;
        } else {
          // 省份维度城市下的站点数量
          displayCount = params.data.cityNum || 1;
        }
        return `<div class="customTooltip">
                  <div class="tooltipTitle">${cityName} ${displayCount}${displayText}</div>
                  <div class="tooltipContent">桩/枪数量 ${
                    params.data.pileCount
                  }/${params.data.pileCount * 2}个</div>
                </div>`;
      }
      return params.name;
    },
    backgroundColor: "transparent",
    borderWidth: 0,
    position: function (position) {
      // 固定在鼠标右上方
      return [position[0] + 10, position[1] - 60];
    },
  };
};

// 显示全国地图
const showNationMap = () => {
  // 地图配置
  const option = {
    backgroundColor: "transparent",
    tooltip: getTooltipConfig(),
    geo: {
      silent: true,
      map: "china",
      roam: false,
      aspectScale: 0.75,
      zoom: 1.2,
      layoutCenter: ["50%", "60%"],
      layoutSize: "120%",
      scaleLimit: {
        min: 1,
        max: 1,
      },
      itemStyle: {
        areaColor: "rgba(20, 41, 87, 0.6)",
        borderColor: "#0692a4",
        borderWidth: 1,
      },
      label: {
        show: true,
        color: "#fff",
      },
      emphasis: {
        itemStyle: {
          areaColor: "#2B91B7",
        },
        label: {
          show: false,
          color: "#fff",
        },
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(20, 41, 87, 0.6)",
            borderColor: "#0692a4",
            borderWidth: 1,
          },
          label: {
            show: false,
          },
          emphasis: {
            label: {
              show: false,
            },
          },
        },
      ],
      // 添加地图区域点击事件
      selectedMode: true,
    },
    series: [
      {
        type: "effectScatter", // 使用 effectScatter 类型
        coordinateSystem: "geo",
        name: "1-10台",
        data: convertStationData(
          props.provinceData.filter(
            (item) => item.pileCount > 0 && item.pileCount <= 10
          )
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(44, 172, 246, 1)",
          borderColor: "rgba(44, 172, 246, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 1,
      },
      {
        type: "effectScatter", // 使用 effectScatter 类型
        coordinateSystem: "geo",
        name: "10-50台",
        data: convertStationData(
          props.mapsData.filter(
            (item) => item.pileCount > 10 && item.pileCount <= 50
          )
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(116, 227, 139, 1)",
          borderColor: "rgba(116, 227, 139, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 2,
      },
      {
        type: "effectScatter", // 使用 effectScatter 类型
        coordinateSystem: "geo",
        name: "50台以上",
        data: convertStationData(
          props.mapsData.filter((item) => item.pileCount > 50)
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(247, 203, 118, 1)",
          borderColor: "rgba(247, 203, 118, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 3,
      },
    ],
  };
  mapInstance.value.setOption(option);
  mapInstance.value.on("click", (params) => {
    if (
      params.componentType === "geo" ||
      (params.name && provinceCoordMap[params.name])
    ) {
      const provinceName = params.name;
      if (provinceName) {
        currentMapLevel.value = "province";
        currentProvince.value = provinceName;
        showProvinceMap(provinceName);
        // 省份点击
        const selectedProvince = props.mapsData.find(
          (item) => item.name === provinceName
        );
        emits("provinceClick", { name: provinceName, data: selectedProvince });
      }
    }
  });
};

// 显示省份地图
const showProvinceMap = (provinceName) => {
  // 根据省份名称选择对应的地图数据
  let provinceMapData;
  switch (provinceName) {
    case "广东省":
      provinceMapData = gd;
      break;
    default:
      console.warn(`暂无${provinceName}的地图数据，使用全国地图代替`);
      return showNationMap();
  }
  // 注册省份地图
  echarts.registerMap(provinceName, provinceMapData);
  // 设置地图实例的配置
  mapInstance.value.setOption({
    geo: {
      silent: true,
      map: provinceName,
    },
  });

  // 地图配置
  const option = {
    backgroundColor: "transparent",
    tooltip: getTooltipConfig(),
    geo: {
      map: provinceName, // 使用省份地图
      roam: false,
      aspectScale: 0.85,
      zoom: 1.2,
      layoutCenter: ["50%", "50%"],
      layoutSize: "100%",
      scaleLimit: {
        min: 1,
        max: 1,
      },
      itemStyle: {
        areaColor: "rgba(20, 41, 87, 0.6)",
        borderColor: "#0692a4",
        borderWidth: 1,
      },
      label: {
        show: true,
        color: "#fff",
      },
      emphasis: {
        itemStyle: {
          areaColor: "#2B91B7",
        },
        label: {
          show: false,
          color: "#fff",
        },
      },
      // 添加地图区域点击事件
      selectedMode: true,
    },
    series: [],
  };

  // 使用 mapsData 数据
  if (props.mapsData && props.mapsData.length > 0) {
    option.series = [
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        name: "1-10台",
        data: convertStationData(
          props.mapsData.filter(
            (item) => item.pileCount > 0 && item.pileCount <= 10
          )
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(44, 172, 246, 1)",
          borderColor: "rgba(44, 172, 246, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 1,
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        name: "10-50台",
        data: convertStationData(
          props.mapsData.filter(
            (item) => item.pileCount > 10 && item.pileCount <= 50
          )
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(116, 227, 139, 1)",
          borderColor: "rgba(116, 227, 139, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 2,
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        name: "50-100台",
        data: convertStationData(
          props.mapsData.filter((item) => item.pileCount > 50)
        ),
        symbolSize: 15,
        symbol: "circle",
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
          scale: 3,
          period: 4,
        },
        itemStyle: {
          color: "rgba(247, 203, 118, 1)",
          borderColor: "rgba(247, 203, 118, 0.3)",
          borderWidth: 8,
        },
        emphasis: {
          itemStyle: {
            color: "#fff",
          },
        },
        zlevel: 3,
      },
    ];
  }
  // 设置配置项
  mapInstance.value.setOption(option);
};

// 将站点数据转换为地图坐标点
function convertStationData(data) {
  const res = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].longitude && data[i].latitude) {
      res.push({
        name: data?.[i]?.stationName || data?.[i]?.city || data?.[i]?.province,
        value: [data[i].longitude, data[i].latitude, data?.[i]?.pileCount || 1],
        count: data?.[i]?.pileCount || 0,
        pileCount: data?.[i]?.pileCount || 0,
        orderCount: data?.[i]?.orderCount || 0,
        cityNum: data?.[i]?.cityNum || 1,
        provinceNum: data?.[i]?.provinceNum || 1,
        cityCount: data?.[i]?.cityCount || 1,
      });
    }
  }
  return res;
}
watch(
  () => props.mapsData,
  (newVal) => {
    if (mapInstance.value) {
      if (currentMapLevel.value === "nation") {
        showNationMap();
      } else {
        showProvinceMap(currentProvince.value);
      }
    }
  },
  { deep: true }
);
// 监听省份ID变化
watch(
  () => props.provinceId,
  (newVal) => {
    fetchStationData();
  }
);
// 获取充电站数据
const fetchStationData = async () => {
  // 根据provinceId决定显示全国还是省份
  if (props.provinceId === 0) {
    currentMapLevel.value = "nation";
    currentProvince.value = null;
  } else {
    currentMapLevel.value = "province";
    currentProvince.value = props.provinceId;
  }
  initMap();
};
onMounted(() => {
  nextTick(() => {
    fetchStationData();
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (mapInstance.value) { 
    mapInstance.value.off("click"); 
    mapInstance.value.dispose();
    mapInstance.value = null; 
  }
})
</script>

<style scoped lang="less">
.mapContent {
  position: relative;
  height: 100%;
  width: 100%;
}
.mapChart {
  width: 100%;
  height: 100%;
  background-color: transparent;
  position: relative;
}
.cardTitle {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  border-left: 4px solid #4e83fd;
  padding-left: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 90%;
  margin: 0 auto;
  .linkIcon {
    font-size: 14px;
    color: #4e83fd;
    cursor: pointer;
  }
}

/* 添加图例样式 */
.mapLegend {
  position: absolute;
  bottom: 10%;
  right: 10%;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px;
  border-radius: 5px;
  z-index: 999;
}

.legendItem {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  &:last-child {
    margin-bottom: 0;
  }
}

.legendDot {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin-right: 8px;

  &.blue {
    background-color: rgba(44, 172, 246, 1);
    box-shadow: 0 0 8px rgba(44, 172, 246, 0.3);
  }

  &.green {
    background-color: rgba(116, 227, 139, 1);
    box-shadow: 0 0 8px rgba(116, 227, 139, 0.3);
  }

  &.yellow {
    background-color: rgba(247, 203, 118, 1);
    box-shadow: 0 0 8px rgba(247, 203, 118, 0.3);
  }
}

.legendText {
  color: #fff;
  font-size: 14px;
}

:deep(.customTooltip) {
  padding: 20px 15px 15px 15px;
  color: #fff;
  font-size: 14px;
  min-width: 180px;
  background: url("@/assets/screen/tooltipBg.png") no-repeat;
  background-size: 100% 100%;
  border-radius: 5px;
}

:deep(.tooltipTitle) {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

:deep(.tooltipContent) {
  font-size: 14px;
  color: #1df9fc;
}
</style>
